import sys

import numpy as np

from PyQt5.QtWidgets import QApplication, QMainWindow

from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas

from matplotlib.figure import Figure

from matplotlib.patches import Rectangle


class SelectBox:

    def __init__(self, ax):

        self.ax = ax

        self.rect = None

        self.press = None

        self.rects = []  # 用于存储所有添加的矩形

    def on_press(self, event):

        if event.inaxes != self.ax:
            return

        self.press = (event.xdata, event.ydata)

    def on_release(self, event):

        if event.inaxes != self.ax:
            return

        if self.press is None:
            return

        x0, y0 = self.press

        x1, y1 = event.xdata, event.ydata

        if x0 > x1:
            x0, x1 = x1, x0

        if y0 > y1:
            y0, y1 = y1, y0

            # 清除之前的矩形

        for rect in self.rects:
            rect.remove()

        self.rects.clear()

        # 添加新的矩形

        self.rect = Rectangle(

            (x0, y0), x1 - x0, y1 - y0,

            edgecolor='r', facecolor='none', linewidth=2

        )

        self.ax.add_patch(self.rect)

        self.rects.append(self.rect)  # 将新矩形添加到列表中

        self.ax.figure.canvas.draw_idle()

    def on_motion(self, event):

        if self.press is None:
            return

        if event.inaxes != self.ax:
            return

        x0, y0 = self.press

        x1, y1 = event.xdata, event.ydata

        # 清除之前的矩形

        for rect in self.rects:
            rect.remove()

        self.rects.clear()

        # 绘制新的矩形（如果鼠标移动）

        if x0 is not None and y0 is not None:
            self.rect = Rectangle(

                (min(x0, x1), min(y0, y1)),

                abs(x1 - x0), abs(y1 - y0),

                edgecolor='r', facecolor='none', linewidth=2

            )

            self.ax.add_patch(self.rect)

            self.rects.append(self.rect)  # 将新矩形添加到列表中

        self.ax.figure.canvas.draw_idle()

class DualAxisWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.fig = Figure(figsize=(5, 4), dpi=100)
        self.ax1 = self.fig.add_subplot(111)

        # 示例数据
        x = np.linspace(0, 10, 100)
        y = np.sin(x)
        self.ax1.plot(x, y)

        # 初始化选择框
        self.select_box = SelectBox(self.ax1)

        # 绑定事件
        self.fig.canvas.mpl_connect('button_press_event', self.select_box.on_press)
        self.fig.canvas.mpl_connect('button_release_event', self.select_box.on_release)
        self.fig.canvas.mpl_connect('motion_notify_event', self.select_box.on_motion)

        self.canvas = FigureCanvas(self.fig)
        self.setCentralWidget(self.canvas)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    mainWin = DualAxisWindow()
    mainWin.show()
    sys.exit(app.exec_())